﻿using System;
using NBuild.Fx.Interfaces;

namespace NBuild.Fx
{
    public abstract class NBuildScript : IBuildScript
    {
        private readonly IBuildEngine _engine;
        private readonly ConsoleColor _originalForeColor;

        protected NBuildScript(IBuildEngine engine)
        {
            _engine = engine;
            _originalForeColor = Console.ForegroundColor;
        }

        #region IDisposable implementation

        ~NBuildScript()
        {
            Dispose(false);
        }

        void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Console.ForegroundColor = _originalForeColor;
        }

        #endregion

        #region IBuildScript implementation

        public void Log(LogType logType, object message, params object[] args)
        {
            ConsoleColor foreColor = LogColors[(int)logType] ?? _originalForeColor;
            Console.ForegroundColor = foreColor;
            string stringMessage = message != null ? message.ToString() : string.Empty;
            Console.WriteLine(stringMessage, args);
        }

        private static readonly ConsoleColor?[] LogColors = new ConsoleColor?[]
        {
            null,
            ConsoleColor.Cyan,
            ConsoleColor.Gray,
            ConsoleColor.Yellow,
            ConsoleColor.Red,
        };

        #endregion

        #region Protected access to IBuildEngine and its members

        protected BuildEnvironment BuildEnvironment
        {
            get { return Engine != null ? Engine.BuildEnvironment : null; }
        }

        protected IBuildEngine Engine
        {
            get { return _engine; }
        }

        protected TTaskSet GetTask<TTaskSet>()
            where TTaskSet : ITaskSet
        {
            return Engine.GetTask<TTaskSet>();
        }

        #endregion
    }
}
